package scatter.errorlog.rest.service.impl;

import cn.hutool.core.exceptions.ExceptionUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import scatter.common.LoginUser;
import scatter.common.rest.security.LoginUserTool;
import scatter.common.rest.service.IBaseAddQueryFormServiceImpl;
import scatter.common.rest.exception.IErrorLogListener;
import scatter.common.rest.tools.ErrorLogCollectorTool;
import scatter.common.rest.tools.RequestTool;
import scatter.errorlog.pojo.form.ErrorLogAddForm;
import scatter.errorlog.pojo.form.ErrorLogPageQueryForm;
import scatter.errorlog.pojo.po.ErrorLog;
import scatter.errorlog.rest.mapper.ErrorLogMapper;
import scatter.errorlog.rest.service.IErrorLogService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * <p>
 * 异常日志表 服务实现类
 * </p>
 *
 * @author yw
 * @since 2021-01-29
 */
@Service
@Transactional
public class ErrorLogServiceImpl extends IBaseAddQueryFormServiceImpl<ErrorLogMapper, ErrorLog, ErrorLogAddForm, ErrorLogPageQueryForm> implements IErrorLogService, IErrorLogListener {
    @Override
    public void preAdd(ErrorLogAddForm addForm,ErrorLog po) {
        super.preAdd(addForm,po);

    }


    @Override
    public void onError(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ErrorLog errorLog = new ErrorLog();
        LoginUser loginUser = LoginUserTool.getLoginUser();
        // 用户信息
        if (loginUser != null) {
            errorLog.setUserId(loginUser.getId());
            errorLog.setUserNickname(loginUser.getNickname());
        }
        // 名称
        Object apiName = ErrorLogCollectorTool.get("apiName");
        errorLog.setName(Optional.ofNullable(apiName).map(o -> o.toString()).orElse(""));
        errorLog.setRequestUrl(request.getRequestURL().toString());
        errorLog.setRequestMethod(request.getMethod());
        errorLog.setRequestHeaders(RequestTool.getHeaderText(request).toString());
        errorLog.setRequestParmas(RequestTool.getRequestParameterText(request).toString());

        errorLog.setRequestBody(toJsonStr(ErrorLogCollectorTool.get("requestBody")));
        errorLog.setRequestIp(RequestTool.getRemoteAddr(request));

        // 异常默认500
        errorLog.setResponseStatus("500");
        errorLog.setResponseBody(toJsonStr(ErrorLogCollectorTool.get("responseBody")));
        errorLog.setExceptionStackTrace(ex == null ? null : ExceptionUtil.stacktraceToString(ex));
        save(errorLog);

    }
}
